package com.xinzhidi.web.ctw.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ctg.ag.sdk.biz.AepDeviceCommandClient;
import com.ctg.ag.sdk.biz.AepDeviceStatusClient;
import com.ctg.ag.sdk.biz.AepNbDeviceManagementClient;
import com.ctg.ag.sdk.biz.aep_device_command.CreateCommandRequest;
import com.ctg.ag.sdk.biz.aep_device_command.CreateCommandResponse;
import com.ctg.ag.sdk.biz.aep_device_status.QueryDeviceStatusRequest;
import com.ctg.ag.sdk.biz.aep_device_status.QueryDeviceStatusResponse;
import com.ctg.ag.sdk.biz.aep_nb_device_management.QueryDeviceByImeiRequest;
import com.ctg.ag.sdk.biz.aep_nb_device_management.QueryDeviceByImeiResponse;
import com.xinzhidi.common.utils.DateUtils;
import com.xinzhidi.common.utils.StringUtils;
import com.xinzhidi.web.ctw.domain.BodyResponse;
import com.xinzhidi.web.ctw.domain.CtwEntity;
import com.xinzhidi.web.ctw.domain.DeviceStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Base64;


/**
 * CTW业务层处理
 *
 * @author cx
 * @date 2023-05-23
 */
@Service
public class CtwService {

    @Autowired
    private CtwEntity ctwEntity;

    /**
     * 根据IMEI查询设备信息
     *
     * @param imei
     * @return
     */
    public String queryDeviceByImei(String imei) {
        String deviceId = "";

        AepNbDeviceManagementClient client = AepNbDeviceManagementClient.newClient()
                .appKey(ctwEntity.getAppKey()).appSecret(ctwEntity.getAppSecret())
                .build();
        QueryDeviceByImeiRequest request = new QueryDeviceByImeiRequest();
        // set your request params here
        request.setParamProductId(ctwEntity.getProductId());
        request.setParamImei(imei);
        request.setParamMasterKey(ctwEntity.getMasterKey());
        try {
            QueryDeviceByImeiResponse response = client.QueryDeviceByImei(request);
            String message = new String(response.getBody());
            JSONObject jsonObject = JSON.parseObject(message);
            if (jsonObject.containsKey("code") && Integer.parseInt(jsonObject.get("code").toString()) == 0) {
                deviceId = (JSON.parseObject(jsonObject.get("result").toString())).get("deviceId").toString();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        client.shutdown();
        return deviceId;
    }

    /**
     * 根据设备id获取室温数据
     *
     * @param deviceId
     * @return
     */
    public BodyResponse getRoomTemperature(String deviceId) {
        BodyResponse bodyResponse = new BodyResponse();
        DeviceStatus deviceStatus = new DeviceStatus();
        //真实室温
        BigDecimal trueTemperature;

        //修正室温
        BigDecimal modifiedTemperature;

        //用户设定温度
        BigDecimal setTemperature;

        //信号强度
        Integer signalStrength;


        AepDeviceStatusClient client = AepDeviceStatusClient.newClient()
                .appKey(ctwEntity.getAppKey()).appSecret(ctwEntity.getAppSecret())
                .build();

        QueryDeviceStatusRequest request = new QueryDeviceStatusRequest();
        JSONObject paramsJson = new JSONObject();
        paramsJson.put("productId", ctwEntity.getProductId());
        paramsJson.put("deviceId", deviceId);
        paramsJson.put("datasetId", ctwEntity.getDatasetId());
//        request.setBody("{\"productId\":\"16883528\",\"deviceId\":\"de2bb1d7c5e5425fa66bb3d32b814f62\",\"datasetId\":\"APPdata\"}".getBytes());
        request.setBody(paramsJson.toString().getBytes());

        QueryDeviceStatusResponse response = null;
        try {
            response = client.QueryDeviceStatus(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String message = new String(response.getBody());
        // more requests
        JSONObject jsonObject = JSON.parseObject(message);
        if (jsonObject.containsKey("code") && Integer.parseInt(jsonObject.get("code").toString()) == 0) {
            bodyResponse.setCode(Integer.parseInt(jsonObject.get("code").toString()));

            String encodedString = (JSON.parseObject(jsonObject.get("deviceStatus").toString())).get("value").toString();
            byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
            String decodedString = new String(decodedBytes);
            if (StringUtils.isNotBlank(decodedString)) {
                trueTemperature = new BigDecimal(decodedString.split(",")[0]).divide(new BigDecimal(100));
                modifiedTemperature = new BigDecimal(decodedString.split(",")[1]).divide(new BigDecimal(100));
                setTemperature = new BigDecimal(decodedString.split(",")[2]).divide(new BigDecimal(100));
                signalStrength = Integer.parseInt(decodedString.split(",")[3]);
                deviceStatus.setTrueTemperature(trueTemperature);
                deviceStatus.setModifiedTemperature(modifiedTemperature);
                deviceStatus.setSetTemperature(setTemperature);
                deviceStatus.setSignalStrength(signalStrength);

                String d = DateUtils.stampToDate((JSON.parseObject(jsonObject.get("deviceStatus").toString())).get("timestamp").toString(), DateUtils.YYYY_MM_DD_HH_MM_SS);
                deviceStatus.setTime(DateUtils.parseDate(d));
                bodyResponse.setDeviceStatus(deviceStatus);
            }
        }
        client.shutdown();
        return bodyResponse;
    }

    /**
     * 发送指令
     *
     * @param deviceId    设备id
     * @param operator    操作人
     * @param uploadCycle 上传周期   单位：秒
     * @param Temperature 温度修正
     * @return
     */
    public boolean sendOrder(String deviceId, Long operator, Integer uploadCycle, Integer Temperature) {
        boolean flag = false;
        AepDeviceCommandClient client = AepDeviceCommandClient.newClient()
                .appKey(ctwEntity.getAppKey()).appSecret(ctwEntity.getAppSecret())
                .build();
        CreateCommandRequest request = new CreateCommandRequest();
        request.setParamMasterKey(ctwEntity.getMasterKey());


        Temperature = Temperature * 100;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("deviceId", deviceId);
        jsonObject.put("operator", operator);
        jsonObject.put("productId", ctwEntity.getProductId());
        jsonObject.put("level", 1);

        JSONObject content = new JSONObject();
        content.put("dataType", 1);
        content.put("payload", uploadCycle + "," + Temperature);
        jsonObject.put("content", content);

        request.setBody(jsonObject.toString().getBytes());
        CreateCommandResponse response = null;
        try {
            response = client.CreateCommand(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String message = new String(response.getBody());
        // more requests
        JSONObject object = JSON.parseObject(message);
        if (object.containsKey("code") && Integer.parseInt(object.get("code").toString()) == 0) {
            flag = true;
        }
        client.shutdown();
        return flag;
    }


}
